package br.edu.unifei.cct810.projetofinal.gui.componentes;

import java.awt.Color;
import java.awt.FontMetrics;

import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.text.TabSet;
import javax.swing.text.TabStop;

import br.edu.unifei.cct810.projetofinal.utils.Constantes;

public class EditorTexto extends javax.swing.JTextPane{
	
	private AbstractDocument doc;
	
	public EditorTexto(String texto)
	{
		AttributeSet df = Constantes.PRETO;
		this.setCharacterAttributes(df, false);	
		this.setText(texto);
		this.setSelectionColor(Color.decode("#10377C"));        
		this.setSelectedTextColor(Color.white);
	}
	
	public AbstractDocument getDoc()
	{
		StyledDocument styledDoc = this.getStyledDocument();
        if (styledDoc instanceof AbstractDocument) {
            this.doc = (AbstractDocument)styledDoc;
        }
        return this.doc;
	}
	
	public int getLineCount(){
		int numeroLinhas = 0;
		for(int i = 0; i < this.getText().length(); i++){
			if(this.getText().charAt(i) == '\n')
				numeroLinhas++;
		}
		return numeroLinhas+1;
	}
	
	public void setTabs(int charactersPerTab){
		FontMetrics fm = this.getFontMetrics(this.getFont());
		int charWidth = fm.charWidth( 'w' );
		int tabWidth = charWidth * charactersPerTab;
 
		TabStop[] tabs = new TabStop[10];
 
		for (int j = 0; j < tabs.length; j++)
		{
			int tab = j + 1;
			tabs[j] = new TabStop( tab * tabWidth );
		}
 
		TabSet tabSet = new TabSet(tabs);
		SimpleAttributeSet attributes = new SimpleAttributeSet();
		StyleConstants.setTabSet(attributes, tabSet);
		int length = this.getDocument().getLength();
		this.getStyledDocument().setParagraphAttributes(0, length, attributes, false);
	}
	
	public void limpaSelecao(){
		if(this.getSelectedText() != ""){
			this.replaceSelection("");
		}		
	}
	
	public String formatacaoTexto(){		
		String texto = this.getText();
		if(!(texto.contains("\r\n")))
			texto = texto.replaceAll("\n","\r\n");
		return texto;
	}
}
